/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Servlet;

import DataAccess.UserAccess;
import Entity.Account;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author phuc
 */
public class AccountServlet extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        UserAccess user = new UserAccess();
        PersistenceManager pm = PMF.get().getPersistenceManager();
        try {
            String action = request.getParameter("action");
            //out.println(action);
            if (action.equals("login"))
            {
                String username = request.getParameter("Username");
                String password = request.getParameter("Password");
                //PersistenceManager pm = PMF.get().getPersistenceManager();
                //out.print("Check login");
                try{
                    Query q = pm.newQuery(Account.class,"username == user && password == pass");
                    q.declareParameters("String user,String pass");
                    List<Account> results = (List<Account>)q.execute(username,password);
                    // If Login successful
                    Account acc = results.get(0);
                    if (results.size() > 0)
                    {
                        out.print("User " + acc.getId());
                        HttpSession session = request.getSession(true);
                        session.setAttribute("uid", acc.getId());
                        response.sendRedirect("/TrangChu.jsp");
                    }
                    else
                        response.sendRedirect("Login.jsp");
                }catch(Exception e)
                {
                    out.print(e.getMessage());
                }
                finally
                {
                    pm.close();
                }
            }
            else if(action.equals("edit"))
            {
                Long ID;
                String password,role,fullname;
                ID = Long.parseLong(request.getParameter("txtID"));
                password = request.getParameter("txtPassword");
                fullname = request.getParameter("txtFullName");
                if (request.getParameter("rdRole").equals("Admin"))
                    role = "admin";
                else
                    role = "user";
                if (user.editUser(ID, password, role, fullname))
                {
                    response.sendRedirect("Account/DisplayAccount.jsp");
                }
            }
            else if (action.equals("change"))
            {
                pm = PMF.get().getPersistenceManager();
                Long ID = Long.parseLong(request.getParameter("txtID")); 
                String newpass = request.getParameter("txtNewPassword").trim();
                String oldpass = request.getParameter("txtOldPassword").trim();
                if (user.changePassword(ID, oldpass, newpass))
                    out.print("Change password successfully. <a href = \"Trangchu.jsp\">Click here</a> to go homepage");
                else
                    response.sendRedirect("Account/ChangePassword.jsp");
                pm.close();
            }
            else if (action.equals("createAdmin"))
            {               
                // Create admin for the first time
                String username = request.getParameter("txtUsername");
                String password = request.getParameter("txtPassword");
                String role = "admin";
                user.addUser(username, password,"administrator", role);
                out.println("Add admin successful ! <a href = \"Login.jsp\">Click here</a> to Login");
            }
            else if (action.equals("create"))// Create account
            {
                String username = request.getParameter("txtUsername");
                String password = request.getParameter("txtPassword");
                String fullname = request.getParameter("txtFullName");
                String role = request.getParameter("rdRole").trim();
                user.addUser(username, password, fullname, role);
                response.sendRedirect("/Account/CreateAccount.jsp");
            }
        } finally { 
            out.close();
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
